package com.pig4cloud.pig.juhe.api.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.sshd.client.SshClient;
import org.apache.sshd.client.session.ClientSession;
import org.apache.sshd.scp.client.ScpClientCreator;
import org.apache.sshd.scp.client.ScpClient;

import java.io.IOException;
import java.time.Duration;
import java.time.Instant;

/**
 * @author yuwenfeng
 * @description: Scp文件传输
 * @date 2022/7/7 14:09
 */
@Slf4j
public class ScpUtil {

	/**
	 * Scp文件传输
	 */
	public static boolean scpFile(String host, String username, String password, int port, String local, String remote) {
		SshClient client = null;
		ClientSession session = null;
		ScpClient scpClient = null;
		try {
			Instant start = Instant.now();
			// 创建 SSH客户端
			client = SshClient.setUpDefaultClient();
			// 启动 SSH客户端
			client.start();
			// 通过主机IP、端口和用户名，连接主机，获取Session
			session = client.connect(username, host, port).verify().getSession();
			// 给Session添加密码
			session.addPasswordIdentity(password);
			// 校验用户名和密码的有效性
			boolean isSuccess = session.auth().verify().isSuccess();
			// 认证成功
			if (isSuccess) {
				Instant middleTime = Instant.now();
				long timeElapsed = Duration.between(start, middleTime).toMillis();
				log.info("Connect host cost time：{}", timeElapsed);
				ScpClientCreator creator = ScpClientCreator.instance();
				// 创建 SCP 客户端
				scpClient = creator.createScpClient(session);
				log.info("Scp beginning");
				// ScpClient.Option.Recursive：递归copy，可以将子文件夹和子文件遍历copy
				scpClient.upload(local, remote, ScpClient.Option.Recursive);
				log.info("Scp finished");
			}else{
				log.error("ScpUtil auth fail");
				return false;
			}
			Instant endTime = Instant.now();
			long timeElapsed = Duration.between(start, endTime).toMillis();
			log.info("Total Cost time：{}", timeElapsed);
			return true;
		} catch (Exception e) {
			log.error("ScpUtil Exception", e);
			return false;
		} finally {
			try {
				// 释放 SCP客户端
				if (null != scpClient) {
					scpClient = null;
				}
				// 关闭 Session
				if (session != null && session.isOpen()) {
					session.close();
				}
				// 关闭 SSH客户端
				if (client != null && client.isOpen()) {
					client.stop();
					client.close();
				}
			} catch (IOException e) {
				log.error("ScpUtil IOException", e);
			}
		}
	}
}
